package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
类简介：

功能：

时间：2020/4/9

*/
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Autowired
    PermissionDao permissionDao;

    @Autowired
    RoleDao roleDao;


    @Override
    public User findByUsername(String username) {
        User user = userDao.findByUsername(username);
        if (user == null){
            return null;
        }

        user.setRoles(roleDao.findRolesById(user.getId()));
        if (user.getRoles() != null){
            for (Role role : user.getRoles()) {
                role.setPermissions(permissionDao.findPermissionsById(role.getId()));
            }
        }
        return user;
    }

    @Override
    public PageResult PageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        if (currentPage == null || currentPage < 1) {
            currentPage = 0;
        }
        if (pageSize == null || pageSize < 1) {
            currentPage = 10;
        }
        if (queryString == null || queryString.trim().equals("")) {
            queryString = "";
        }

        //分页查询使用分页助手
        PageHelper.startPage(currentPage, pageSize);
        //queryString %xxx%
        Page<User> page = userDao.selectByCondition("%" + queryString.trim() + "%");

        long total = page.getTotal();
        List<User> rows = page.getResult();

        return new PageResult(total, rows);
    }

    @Override
    public void add(User user, Integer[] roleIds) {
        /*//判断用户名是否存在
        User u = userDao.findByUsername(user.getUsername());
        if (u!=null) {
            //代表用户名重复不能添加
            throw new RuntimeException("用户名已经存在,请勿重复添加");
        }*/
        //判断手机号是否存在
        Integer count = userDao.findByTel(user.getTelephone());
        if (count > 0) {
            //代表编码重复不能添加
            throw new RuntimeException("手机号已经存在，请更换手机号");
        }

        if (user.getPassword()!=null){
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        }
        //保存 项目组表中添加新数据  此时user中没有id值
        userDao.add(user);
        //添加完之后 返回一个自动生成的id并包装到checkGroup中
        Integer userId = user.getId();
        //建立检查组与检查项之间的关系信息
        setUserAndRole(roleIds, userId);
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findRoleIdsByUserId(Integer id) {
        return userDao.findRoleIdsByUserId(id);
    }

    @Override
    public void editUser(User user, Integer[] roleIds) {

        //判断手机号是否超过两个是否存在
        Integer count = userDao.findByTel(user.getTelephone());
        if (count > 1) {
            //代表编码重复不能添加
            throw new RuntimeException("手机号已经存在，请重新输入手机号");
        }
        //密码加密
        if (user.getPassword().length()<=12){
            user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        }
        //更新用户信息
        userDao.edit(user);
        //删除关联表中所有数据
        userDao.deleteAssociation(user.getId());
        //重新建立关联关系
        setUserAndRole(roleIds,user.getId());
    }

    @Override
    public void delete(Integer id) {
        userDao.deleteAssociation(id);
        userDao.deleteUserById(id);
    }

    /**
     * 抽取出来的   用于建立用户和角色之间的关系
     * @param roleIds 用户包含的角色id
     * @param userId 用户id
     */
    public void setUserAndRole(Integer[] roleIds, Integer userId) {
        if (roleIds != null && roleIds.length > 0) {
            for (Integer  roleId: roleIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("user_id",userId);
                map.put("role_id", roleId);
                try {
                    userDao.addUserAndRole(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException("网络繁忙,请稍后再试");
                }

            }
        }
    }
}
